// controller
package controller

import (
	"fmt"
	"reflect"
	"runtime/debug"
)

type Controller struct {
	AppController interface{}
}

// 路由：对action的路由分发控制
func (c *Controller) Route(action string, b []byte) (code int, rsData string) {
	defer func() {
		if err := recover(); err != nil {
			code = 0
			rsData = fmt.Sprint(err)
			fmt.Println(err)
			debug.PrintStack()
			return
		}
	}()
	if c.AppController == nil {
		// 当没有指定，则走通用接口
		commonMethod := reflect.ValueOf(c).MethodByName(action)
		if commonMethod.IsValid() {
			in := make([]reflect.Value, 1)
			in[0] = reflect.ValueOf(b)
			call := commonMethod.Call(in)
			code = call[0].Interface().(int)
			rsData = call[1].Interface().(string)
		} else {
			code = 0
			rsData = "Error::not this action of common's api ![" + action + "]"
		}
	} else {
		// 如果指定了，则先判断指定的控制器是否存在这个action
		fmt.Println(reflect.ValueOf(c.AppController))
		appMethod := reflect.ValueOf(c.AppController).MethodByName(action)
		if appMethod.IsValid() {
			in := make([]reflect.Value, 1)
			in[0] = reflect.ValueOf(b)
			callRs := appMethod.Call(in)
			code = callRs[0].Interface().(int)
			rsData = callRs[1].Interface().(string)
		} else {
			commonMethod := reflect.ValueOf(c).MethodByName(action)
			if commonMethod.IsValid() {
				in := make([]reflect.Value, 1)
				in[0] = reflect.ValueOf(b)
				call := commonMethod.Call(in)
				code = call[0].Interface().(int)
				rsData = call[1].Interface().(string)
			} else {
				code = 0
				rsData = "Error::not this action of private's api ![" + action + "]"
			}
		}
	}
	return
}
